<?php

class image_mdl_image extends dbeav_model {

    var $has_tag = true;

    var $has_many = array(
        'tag' => 'tag_rel@desktop:replace:image_id^rel_id'
    );

    var $defaultOrder = array(
        'last_modified',
        'desc'
    );

    function store($file, $image_id, $size = null, $name = null, $watermark = false) {
        if (! defined(FILE_STORAGER))
            define('FILE_STORAGER', 'filesystem');
        list ($w, $h, $t) = getimagesize($file);
        
        $extname = array(
            1 => '.gif',
            2 => '.jpg',
            3 => '.png',
            6 => '.bmp'
        );
        
        if (! isset($extname[$t])) {
            return false;
        }
        
        if ($image_id) {
            $params = $this->dump($image_id);
            if ($name)
                $params['image_name'] = $name;
            $params['image_id'] = $image_id;
        } else {
            $params['image_id'] = $this->gen_id();
            $params['image_name'] = $name;
            $params['storage'] = FILE_STORAGER;
        }
        if (substr($file, 0, 4) == 'http') {
            $params['storage'] = 'network';
            $params['url'] = $file;
            $params['ident'] = $file;
            $params['width'] = $w;
            $params['height'] = $h;
            $this->save($params);
            return $params['image_id'];
        }
        
        $params['watermark'] = $watermark;
        if (is_bool($params['watermark'])) {
            $params['watermark'] = $params['watermark'] ? 'true' : 'false';
        }
        $storager = new base_storager();
        $params['last_modified'] = time();
        list ($url, $ident, $no) = explode("|", $storager->save_upload($file, 'image', '', $msg, $extname[$t]));
        if ($size) {
            $size = strtolower($size);
            $params[$size . '_url'] = $url;
            $params[$size . '_ident'] = $ident;
        } else {
            $params['url'] = $url;
            $params['ident'] = $ident;
            $params['width'] = $w;
            $params['height'] = $h;
        }
        parent::save($params);
        return $params['image_id'];
    }

    function rebuild($image_id, $sizes, $watermark = true) {
        $storager = new base_storager();
        logger::info("Run image rebuild start step 1 : " . $image_id);
        if ($sizes) {
            
            $cur_image_set = $this->app->getConf('image.set');
            $allsize = $this->app->getConf('image.default.set');
            
            $this->watermark_define = array();
            $this->watermark_default = '';
            
            $tmp_target = tempnam(TMP_DIR, 'img');
            $img = $this->dump($image_id);
            if (is_array($img))
                $org_file = $img['url'];
            if (defined("QUEUE_COMSUME_ENV") && constant('QUEUE_COMSUME_ENV'))
                $org_file = ROOT_DIR . "/" . $org_file;
            if (substr($org_file, 0, 4) == 'http') {
                logger::info("Run image rebuild at network image : " . $org_file);
                
                if ($img['storage'] == 'network') {
                    $response = kernel::single('base_httpclient')->get($org_file);
                    if ($response === false) {
                        $data = array(
                            'image_id' => $image_id,
                            'last_modified' => time()
                        );
                        parent::save($data);
                        return true;
                    }
                    $image_content = $response;
                } else {
                    $image_file = $storager->worker->getFile($img['ident'], 'image');
                    if (! $image_file)
                        return false;
                    $image_content = file_get_contents($image_file);
                }
                $org_file = tempnam(TMP_DIR, 'imgorg');
                file_put_contents($org_file, $image_content);
            }
            
            if (! file_exists($org_file)) {
                logger::info("Run image rebuild not find org_file : " . $org_file);
                $data = array(
                    'image_id' => $image_id,
                    'last_modified' => time()
                );
                @unlink($tmp_target);
                // parent::save($data);
                return true;
            }
            logger::info("Run image rebuild find org_file : " . $org_file);
            foreach ($sizes as $s) {
                logger::info("Run image rebuild for sitze:" . $s);
                if (isset($allsize[$s])) {
                    
                    $w = $cur_image_set[$s]['width'];
                    $h = $cur_image_set[$s]['height'];
                    $wh = $allsize[$s]['height'];
                    $wd = $allsize[$s]['width'];
                    $w = $w ? $w : $wd;
                    $h = $h ? $h : $wh;
                    image_clip::image_resize($this, $org_file, $tmp_target, $w, $h);
                    if ($watermark && $cur_image_set[$s]['wm_type'] != 'none' && ($cur_image_set[$s]['wm_text'] || $cur_image_set[$s]['wm_image'])) {
                        $watermark = true;
                        image_clip::image_watermark($this, $tmp_target, $cur_image_set[$s]);
                    }
                    $this->store($tmp_target, $image_id, $s, null, $watermark);
                    
                    @unlink(ROOT_DIR . '/' . $img[strtolower($s) . '_url']);
                }
            }
            @unlink($tmp_target);
            if (strpos($org_file, 'imgorg') !== false)
                @unlink($org_file);
        }
    }

    function fetch($image_id, $size = null) {
        $img = $this->dump($image_id);
        $k = $size ? (strtolower($size) . '_ident') : 'ident';
        if ($img['storage'] == 'network') {
            $response = kernel::single('base_httpclient')->get($img['url']);
            if ($response === false) {
                $data = array(
                    'image_id' => $image_id,
                    'last_modified' => time()
                );
                parent::save($data);
                return true;
            }
            $image_content = $response;
        } else {
            $storager = new base_storager();
            $image_file = $storager->worker->getFile($img[$k], 'image');
            $image_content = file_get_contents($image_file);
        }
        $target_file = tempnam(TMP_DIR, 'targetfile');
        file_put_contents($target_file, $image_content);
        return $target_file;
    }

    function attach($image_id, $target_type, $target_id) {}

    function gen_id() {
        return md5(rand(0, 9999) . microtime());
    }

    function all_storages() {
        return;
    }

    function modifier_storage(&$list) {
        $all_storages = $this->all_storages();
        $all_storages['network'] = app::get('image')->_('远程');
        $list = (array) $list;
        foreach ($list as $k => $v) {
            $list[$k] = $all_storages[$k];
        }
    }

    public function delete_image($image_id, $target_type) {
        if (! $image_id || ! $target_type)
            return true;
        
        $filter = array(
            'image_id' => $image_id,
            'target_type|ne' => $target_type
        );
        $obj_image_attachment = $this->app->model('image_attach');
        $tmp = $obj_image_attachment->getList('*', $filter);
        if ($tmp)
            return true;
        
        $tmp = $this->getList('*', array(
            'image_id' => $image_id,
            'storage' => 'filesystem'
        ));
        // 这里系统会查询一次图片表，如果搜索到表格中还有图片记录，则删除图片，如果没有搜索到信息，说明该图片的记录已经不存在了，直接返回已删除
        if ($tmp) {
            if (file_exists(ROOT_DIR . '/' . $tmp[0]['url']))
                @unlink(ROOT_DIR . '/' . $tmp[0]['url']);
            if (file_exists(ROOT_DIR . '/' . $tmp[0]['l_url']))
                @unlink(ROOT_DIR . '/' . $tmp[0]['l_url']);
            if (file_exists(ROOT_DIR . '/' . $tmp[0]['m_url']))
                @unlink(ROOT_DIR . '/' . $tmp[0]['m_url']);
            if (file_exists(ROOT_DIR . '/' . $tmp[0]['s_url']))
                @unlink(ROOT_DIR . '/' . $tmp[0]['s_url']);
        } else {
            // 如果数据库图片表中找不到该数据，返回已删除，
            // 因为当图片已删除时，这里的delete传入的filter会被dbeav重新去数据库查找一次，从而生成一个array('image_id'=>null)这样的filter，这时候就会把级联删除的所有表的内容全部清空。
            $tmp = $this->getList('image_id', array(
                'image_id' => $image_id
            ));
            if (! $tmp)
                return 1;
        }
        return $this->delete(array(
            'image_id' => $image_id,
            'storage' => 'filesystem'
        ));
    }

    public function pre_delete($data) {
        if ($data) {
            if (file_exists(ROOT_DIR . '/' . $data['url']))
                @unlink(ROOT_DIR . '/' . $data['url']);
            if (file_exists(ROOT_DIR . '/' . $tmp['l_url']))
                @unlink(ROOT_DIR . '/' . $tmp['l_url']);
            if (file_exists(ROOT_DIR . '/' . $tmp['m_url']))
                @unlink(ROOT_DIR . '/' . $tmp['m_url']);
            if (file_exists(ROOT_DIR . '/' . $tmp['s_url']))
                @unlink(ROOT_DIR . '/' . $tmp['s_url']);
        }
        return true;
    }
}
